package com.yupi.springbootinit.controller.graph;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

@RestController
@CrossOrigin
public class JsonFileController {

    private final ResourceLoader resourceLoader;
    private final ObjectMapper objectMapper;

    public JsonFileController(ResourceLoader resourceLoader, ObjectMapper objectMapper) {
        this.resourceLoader = resourceLoader;
        this.objectMapper = objectMapper;
    }

    @GetMapping("/graph")
    public ResponseEntity<ObjectNode> loadJson() {
        try {
            // 加载本地 JSON 文件
            Resource resource = resourceLoader.getResource("classpath:data2.json");
            ObjectNode jsonNode = objectMapper.readValue(resource.getInputStream(), ObjectNode.class);
            return ResponseEntity.ok(jsonNode);
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseEntity.status(500).body(null);
        }
    }
}